package com.cc.reggie.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author kitic
 * @version 1.0
 * @date 2022/7/17  14:03
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
//    @Bean
//    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){
//        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
//        //默认的Key序列化器为: JdkSerializationRedisSerializer
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setConnectionFactory( connectionFactory) ;
//        return redisTemplate;
//    }
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    StringRedisSerializer stringSer = new StringRedisSerializer();
    // JSON 序列化（对象 <-> json 字符串）
    GenericJackson2JsonRedisSerializer jsonSer = new GenericJackson2JsonRedisSerializer();

    // key、hashKey 统一字符串
    template.setKeySerializer(stringSer);
    template.setHashKeySerializer(stringSer);

    // value、hashValue 用 JSON
    template.setValueSerializer(jsonSer);
    template.setHashValueSerializer(jsonSer);

    template.afterPropertiesSet();
    return template;
}
}
